package com.shigen.demo.util.serializer;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import java.io.IOException;
import java.text.DecimalFormat;

public class CustomFileSizeSerializer extends JsonSerializer<Long> {

  @Override
  public void serialize(Long fileSize, JsonGenerator gen, SerializerProvider serializers) throws IOException {
    if (fileSize != null && fileSize > 0L) {
      DecimalFormat df = new DecimalFormat("#.00");
      String fileSizeString = "";
      if (fileSize < 1024) {
        fileSizeString = df.format((double) fileSize) + "B";
      } else if (fileSize < 1048576) {
        fileSizeString = df.format((double) fileSize / 1024) + "KB";
      } else if (fileSize < 1073741824) {
        fileSizeString = df.format((double) fileSize / 1048576) + "MB";
      } else {
        fileSizeString = df.format((double) fileSize / 1073741824) + "GB";
      }
      gen.writeString(fileSizeString);
    } else {
      gen.writeString("0B");
    }
  }
}
